package com.barnett.view;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.Canvas;
import android.graphics.ColorMatrix;
import android.graphics.ColorMatrixColorFilter;
import android.graphics.Paint;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.NinePatchDrawable;
import android.graphics.drawable.StateListDrawable;
import android.util.AttributeSet;
import android.widget.Button;

/**
 * 自动添加点击效果
 * @author jiangjian
 */
public class MyButton extends Button {

	public MyButton(Context context) {
		super(context);
		initMyButton();
	}

	public MyButton(Context context, AttributeSet attrs) {
		super(context, attrs);
		initMyButton();
	}

	public MyButton(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		initMyButton();
	}

	public void setButtonBackground() {
		setBackgroundDrawable(newSelector());
	}

	private void initMyButton() {
		setBackgroundDrawable(newSelector());
	}

	/**
	 * drawable转换为bitmap
	 * 
	 * @param drawable
	 * @return
	 */
	private Drawable drawable2Bitmap(Drawable drawable) {
		Bitmap srcBitmap = null;
		if (drawable instanceof BitmapDrawable) {
			srcBitmap = ((BitmapDrawable) drawable).getBitmap();
		} else if (drawable instanceof NinePatchDrawable) {
			srcBitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(),
					drawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
			Canvas canvas = new Canvas(srcBitmap);
			drawable.setBounds(0, 0, drawable.getIntrinsicWidth(),
					drawable.getIntrinsicHeight());
			drawable.draw(canvas);
		}

		Bitmap bmp = Bitmap.createBitmap(srcBitmap.getWidth(),
				srcBitmap.getHeight(), Config.ARGB_8888);
		float contrast = (float) ((40 + 64) / 128.0);
		ColorMatrix cMatrix = new ColorMatrix();
		cMatrix.set(new float[] { contrast, 0, 0, 0, 0, 0, contrast, 0, 0, 0,// 改变对比
				0, 0, contrast, 0, 0, 0, 0, 0, 1, 0 });

		Paint paint = new Paint();
		paint.setColorFilter(new ColorMatrixColorFilter(cMatrix));

		Canvas canvas = new Canvas(bmp);
		// 在Canvas上绘制一个已经存在的Bitmap。这样，dstBitmap就和srcBitmap
		canvas.drawBitmap(srcBitmap, 0, 0, paint);
		return new BitmapDrawable(bmp);
	}

	/** 设置Selector */
	private StateListDrawable newSelector() {
		StateListDrawable bg = new StateListDrawable();
		Drawable normal = getBackground();
		Drawable pressed;
		pressed = (drawable2Bitmap(getBackground()));
		// View.PRESSED_ENABLED_STATE_SET
		bg.addState(new int[] { android.R.attr.state_pressed,
				android.R.attr.state_enabled }, pressed);
		// View.ENABLED_STATE_SET
		bg.addState(new int[] { android.R.attr.state_enabled }, normal);
		// View.EMPTY_STATE_SET
		bg.addState(new int[] {}, normal);
		return bg;
	}
}
